package cn.itcast.quartz.listener;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.matchers.EverythingMatcher;
import org.quartz.impl.matchers.KeyMatcher;

public class MySchedulerDemoJobListener {

    public static void main(String[] args) throws SchedulerException {
        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();

        JobDetail job = JobBuilder.newJob(MyJob.class).withIdentity("myJob", "group1").build();

        SimpleTrigger trigger = TriggerBuilder.newTrigger().withIdentity("mytrigger", "group1")
                .startNow()
                .withSchedule(SimpleScheduleBuilder.simpleSchedule().repeatSecondlyForever(5))
                .build();

        scheduler.scheduleJob(job, trigger);


        ListenerManager listenerManager = scheduler.getListenerManager();

        //创建并注册一个全局的Job Listener
        //listenerManager.addJobListener(new MyJobListener());
        //创建并注册一个指定任务的Job Listener
        listenerManager.addJobListener(new MyJobListener(), KeyMatcher.keyEquals(JobKey.jobKey("myJob", "group1")));

        // 创建并注册一个全局的Trigger Listener
        //listenerManager.addTriggerListener(new MyTriggerListener("MyTriggerListener"), EverythingMatcher.allTriggers());

        // 创建并注册一个局部的Trigger Listener
        listenerManager.addTriggerListener(new MyTriggerListener("MyTriggerListener"), KeyMatcher.keyEquals(TriggerKey.triggerKey("trigger1", "group1")));

        // 创建SchedulerListener
        listenerManager.addSchedulerListener(new MySchedulerListener());

        // 移除对应的SchedulerListener
        // scheduler.getListenerManager().removeSchedulerListener(new MySchedulerListener());

        // 5：开启
        scheduler.start();
        // 延迟7秒后关闭
        try {
            Thread.sleep(7000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        // 关闭
        scheduler.shutdown();

    }
}
